/*
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package be.free.ts.support;

import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.mappings.converters.Converter;
import org.eclipse.persistence.sessions.Session;
import org.joda.time.DateTime;

import java.util.Date;

/**
 * @author Christophe De Blende
 * @since 08/12/12
 */
public class DateTimeConverter implements Converter {

	@Override
	public Object convertDataValueToObjectValue(Object dataValue, Session session) {
		if (dataValue == null) {
			return null;
		}

		if (dataValue instanceof Date) {
			return new DateTime(dataValue);
		}

		throw new IllegalStateException("Conversion exception, value is not of java.util.Date type.");

	}

	@Override
	public Object convertObjectValueToDataValue(Object objectValue, Session session) {
		if (objectValue == null) {
			return null;
		}

		if (objectValue instanceof DateTime) {
			return ((DateTime) objectValue).toDate();
		}
		throw new IllegalStateException("Conversion exception, value is not of org.joda.time.DateTime type.");
	}

	@Override
	public void initialize(DatabaseMapping dm, Session session) {
		dm.getField().setType(java.sql.Timestamp.class);
	}

	@Override
	public boolean isMutable() {
		return false;
	}

}